import { ref, reactive, computed, watch } from 'vue'
import { defineStore } from 'pinia';
import { MessageItem, MessageType, SessionItem } from '@/services/type';
import { userSessionStore } from '@/stores/session';
import { computedTimeBlock } from '@/utils/computedTime';
import { api } from '@/services/api';

import cloneDeep from 'lodash/cloneDeep';
import { ElMessage } from 'element-plus';

export const pageSize = 20

export const useChatStore = defineStore('chat', () => {

    const sessionStore = userSessionStore();

    // 是否展示聊天框
    const isShowChatBox = ref(false);
    // 是否加载数据
    const isLoading = ref(false);
    // 是否最后一页
    const isLast = ref(false);
    // 游标值
    const cursor = ref('');
    // 消息列表
    let chatMessageList = reactive<MessageItem[]>([]);
    // 当前消息回复
    const currentMsgReply = ref<Partial<MessageType>>({})
    // 最新消息Map
    const messageMap = reactive<Map<number, MessageItem>>(new Map());
    // 当前会话信息
    const currentSession = computed(() => sessionStore.currentSessionInfo);
    // 当前会话ID
    const currentSessionId = computed(() => sessionStore.currentSession.session_id);

    // 监听当前会话ID改变事件
    watch(currentSession, async (val, oldVal) => {
        if (val !== undefined && val !== oldVal) {
            // 初始化会话消息参数
            initParam();
            // 获取聊天消息
            await getMessageList(val.session_id);
            // 切换会话，滚动到底部
            chatListToBottomAction.value?.();
        }
        // 重置当前回复的消息
        currentMsgReply.value = {}
    });

    // 打开聊天框
    const openChatBox = async (receiveUid?: string) => {
        // 展示聊天框
        isShowChatBox.value = true;
        // 如果接收者不为空
        if(receiveUid) {
            // 检查会话信息
            const response = await api.chat.checkSession({ receiveUid });
            if(response.code === 0) {
                // 获取会话详情信息
                let result = await api.chat.sessionDetail({ sessionId: response.data });
                if(result.code != 0) return;
                const session: SessionItem = result.data;
                // 获取下标
                const index = sessionStore.sessionList.findIndex((item) => item.session_id === session.session_id);
                if (index !== -1) {
                    const item = sessionStore.sessionList.splice(index, 1)[0];
                    sessionStore.sessionList.unshift(item);
                } else if(session) {
                    const newItem = cloneDeep(session)
                    newItem.active_time = Date.now()
                    sessionStore.sessionList.unshift(newItem)
                }
                // 默认当前对话
                sessionStore.currentSession.session_id = response.data;
            } else {
                ElMessage.error("不能与自己对话！")
            }
        }
    }

    // 关闭聊天框
    const closeChatBox = () => {
        isShowChatBox.value = false;
    }

    // 查找消息在列表里面的索引
    const getMsgIndex = (msgId: number) => {
        if (!msgId || isNaN(Number(msgId))) return -1
        return chatMessageList.findIndex((item) => item.message.id === msgId)
    }

    // 初始化参数
    const initParam = () => {
        chatMessageList.length = 0;
        isLoading.value = false;
        isLast.value = false;
        cursor.value = '';
    }

    // 获取会话消息列表
    const getMessageList = async (session_id: number, size = pageSize) => {
        // 如果是最后一页，则退出方法
        if(isLast.value) {
            return;
        }
        // 加载数据
        isLoading.value = true;
        const response = await api.chat.queryMessageList({
            session_id,
            pageSize: size,
            cursor: cursor.value
        });
        if(response.code === 0) {
            // 为保证获取的历史消息在前面
            chatMessageList.unshift(...computedTimeBlock(response.data.list));
            // 关闭加载中
            isLoading.value = false;
            // 是否最后一页
            isLast.value = response.data.isLast;
            // 游标值
            cursor.value = response.data.cursor;
        }
    }

    // 推送消息
    const pushMsg = async (data: MessageItem) => {
        // 将最新聊天信息添加到map集合中
        messageMap.set(data.message.sessionId, data);
        // 如果当前会话信息不为空，并且当前会话ID与推送信息会话ID相同
        if(currentSession.value 
            && currentSession.value.session_id === data.message.sessionId
        ) {
            // 将最新聊天信息添加到list集合中
            chatMessageList.push(...computedTimeBlock([ data ], true));
        }
        // 发完消息就要刷新会话列表，
        // 如果当前会话已经置顶了，可以不用刷新
        if(currentSession.value
            && currentSession.value.session_id !== data.message.sessionId
        ) {
            // 获取会话详情信息
            let result = await api.chat.sessionDetail({ sessionId: data.message.sessionId });
            // 更新会话信息时间
            sessionStore.updateSessionLastActiveTime(data.message.sessionId, result.data);
        }

        // 聊天记录计数
        if (currentSessionId.value !== data.message.sessionId) {
            const item = sessionStore.sessionList.find((item) => item.session_id === data.message.sessionId);
            if (item) {
                item.unread_count += 1
            }
        }

        // 聊天列表滚动到底部
        setTimeout(() => {
            // 如果超过一屏了，不自动滚动到最新消息。
            chatListToBottomAction.value?.()
        }, 0)
    }

    // 外部提供消息列表滚动到底部事件
    const chatListToBottomAction = ref<() => void>() 

    return { 
        isShowChatBox, 
        isLoading,
        messageMap,
        currentMsgReply,
        chatMessageList, 
        getMessageList, 
        openChatBox,
        closeChatBox,
        getMsgIndex,
        pushMsg, 
        chatListToBottomAction 
    }
});